package com.example.yichuangyun.mvvm.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentCallDetailsTextBinding;
import com.example.yichuangyun.dialog.ChooseModelDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.call.AliDecompressedCallRecordModel;
import com.example.yichuangyun.model.call.AliSentenceModel;
import com.example.yichuangyun.model.call.DbDecompressedCallRecordModel;
import com.example.yichuangyun.model.call.DbUtterancesModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.activity.CallRecordActivity;
import com.example.yichuangyun.mvvm.ui.adapter.AliCallTextAdapter;
import com.example.yichuangyun.mvvm.ui.adapter.DbCallTextAdapter;
import com.example.yichuangyun.mvvm.ui.fragment.view.CallDetailsTextViewModel;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 通话详情沟通记录--语音转文字
 */
public class CallDetailsTextFragment extends BaseFragment<FragmentCallDetailsTextBinding, CallDetailsTextViewModel> {

    private static final int MAX_REQUESTS = 20;
    private int requestCount = 0;
    private Handler handler;
    /**
     * 默认是豆包模型
     */
    private boolean isDb = true;
    private DbCallTextAdapter dbCallTextAdapter;
    private AliCallTextAdapter aliCallTextAdapter;
    private List<AliSentenceModel> aliTextData = new ArrayList<>();
    private List<DbUtterancesModel> dbTextData = new ArrayList<>();
    /**
     * 音频地址
     */
    private String url, id;
    private boolean isFirstRequest = true;
    private String requestId = "";

    public static CallDetailsTextFragment newInstance(String id, String url) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.idKey, id);
        bundle.putString(Constant.urlKey, url);
        CallDetailsTextFragment fragment = new CallDetailsTextFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected CallDetailsTextViewModel bindModel() {
        return getViewModel(this, CallDetailsTextViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initData() {
        handler = new Handler();
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString(Constant.idKey);
            url = bundle.getString(Constant.urlKey);
            viewModel.getTranscription(id, url, -1, null);
        }
        dbCallTextAdapter = new DbCallTextAdapter(mContext);
        binding.dbRv.setAdapter(dbCallTextAdapter);
        aliCallTextAdapter = new AliCallTextAdapter(mContext);
        binding.aliRv.setAdapter(aliCallTextAdapter);
    }

    @Override
    protected void initClick() {
        viewModel.transTextSuccess.observe(this, callRecordTransModel -> {
            if (callRecordTransModel != null) {
                if (!TextUtils.isEmpty(callRecordTransModel.getRequestId())) {
                    requestId = callRecordTransModel.getRequestId();
                    if (isFirstRequest) {
                        isDb = requestId.equals("DB");
                        binding.changeModelTv.setText(mContext.getString(isDb ? R.string.db_model : R.string.ali_model));
                        binding.modelIv.setImageResource(isDb ? R.mipmap.icon_db : R.mipmap.icon_ali2);
                        if (!TextUtils.isEmpty(callRecordTransModel.getAnalyseResult())) {
                            EventBus.getDefault().post(new EventBusModel(callRecordTransModel.getAnalyseResult(), 100));
                        }
                    }
                    if (!TextUtils.isEmpty(callRecordTransModel.getDbCompressedJson())) {
                        DbDecompressedCallRecordModel dbRecord = new Gson().fromJson(callRecordTransModel.getDbCompressedJson(), DbDecompressedCallRecordModel.class);
                        if (dbRecord != null && dbRecord.getResult() != null && dbRecord.getResult().getUtterances() != null && !dbRecord.getResult().getUtterances().isEmpty()) {
                            dbTextData = dbRecord.getResult().getUtterances();
                            // hasDuplicate=true 声道有问题 全部手动改为左声道
                            if (dbRecord.getResult().getHasDuplicate()) {
                                for (DbUtterancesModel model : dbTextData) {
                                    if (model != null && model.getAdditions() != null) {
                                        model.getAdditions().setChannelId("1");
                                        model.setHasDuplicate(true);
                                    }
                                }
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(callRecordTransModel.getCompressedJson())) {
                        AliDecompressedCallRecordModel aliRecord = new Gson().fromJson(callRecordTransModel.getCompressedJson(), AliDecompressedCallRecordModel.class);
                        if (aliRecord != null && aliRecord.getTranscripts() != null && !aliRecord.getTranscripts().isEmpty()) {
                            aliTextData = aliRecord.getTranscripts().get(0).getSentences();
                        }
                    }
                    if (isDb) {
                        binding.changeModelTv.setText(R.string.db_model);
                        binding.modelIv.setImageResource(R.mipmap.icon_db);
                        if (!dbTextData.isEmpty()) {
                            EventBus.getDefault().post(new EventBusModel(Constant.ALREADY_TRANS_TEXT, 101));
                            changeModel();
                        }
                    } else {
                        binding.changeModelTv.setText(mContext.getString(R.string.ali_model));
                        binding.modelIv.setImageResource(R.mipmap.icon_ali2);
                        EventBus.getDefault().post(new EventBusModel(Constant.ALREADY_TRANS_TEXT, 101));
                        if (!aliTextData.isEmpty()) {
                            changeModel();
                        }
                    }
                } else {
                    binding.transLl.setVisibility(View.VISIBLE);
                    binding.transTv.setText(getString(R.string.click_trans_text));
                    binding.modelTipsLl.setVisibility(View.GONE);
                    binding.dbRv.setVisibility(View.GONE);
                    binding.aliRv.setVisibility(View.GONE);
                }
            }
            isFirstRequest = false;
        });

        viewModel.mErrorData.observe(this, s -> {
            isFirstRequest = false;
            binding.modelTipsLl.setVisibility(View.VISIBLE);
            binding.dbRv.setVisibility(View.GONE);
            binding.aliRv.setVisibility(View.GONE);
            binding.transLl.setVisibility(View.VISIBLE);
            binding.transLl.setBackgroundResource(R.drawable.shape_1ae55c5c_50dp_bg);
            binding.transIv.setImageResource(R.mipmap.icon_exe);
            binding.transTv.setText(getString(R.string.file_exception));
            binding.transTv.setTextColor(ContextCompat.getColor(mContext, R.color.color_E55C5C));
        });

        viewModel.requestAgain.observe(this, s -> {
            if (requestCount < MAX_REQUESTS) {
                requestCount++;
                isFirstRequest = false;
                // 延迟 10 秒后再次进行网络请求
                handler.postDelayed(this::getTranscription, 10000);
            } else {
                isFirstRequest = false;
                binding.modelTipsLl.setVisibility(View.VISIBLE);
                binding.dbRv.setVisibility(View.GONE);
                binding.aliRv.setVisibility(View.GONE);
                binding.transLl.setVisibility(View.VISIBLE);
                binding.transLl.setBackgroundResource(R.drawable.shape_1ae55c5c_50dp_bg);
                binding.transIv.setImageResource(R.mipmap.icon_exe);
                binding.transTv.setText(getString(R.string.file_exception));
                binding.transTv.setTextColor(ContextCompat.getColor(mContext, R.color.color_E55C5C));
            }
        });

        // 语音转文字
        viewModel.onDelayClick(binding.transLl, o -> {
            if (binding.transTv.getText().toString().equals(getString(R.string.click_trans_text))) {
                getTranscription();
            }
        });

        viewModel.onDelayClick(binding.changeModelLl, o -> {
            ChooseModelDialog chooseModelDialog = new ChooseModelDialog(mContext, isDb) {
                @Override
                public void chooseModel(boolean b) {
                    isDb = b;
                    binding.changeModelTv.setText(mContext.getString(isDb ? R.string.db_model : R.string.ali_model));
                    binding.modelIv.setImageResource(isDb ? R.mipmap.icon_db : R.mipmap.icon_ali2);
                    if (!isDb && aliTextData.isEmpty()) {
                        getTranscription();
                        return;
                    }
                    if (isDb && dbTextData.isEmpty()) {
                        getTranscription();
                        return;
                    }
                    changeModel();
                }
            };
            chooseModelDialog.show();

        });
    }

    private void getTranscription() {
        binding.dbRv.setVisibility(View.GONE);
        binding.aliRv.setVisibility(View.GONE);
        //正在识别中
        binding.transLl.setVisibility(View.VISIBLE);
        binding.transLl.setBackgroundResource(R.drawable.shape_4371ff_50dp_bg);
        Glide.with(this)
                .asGif()
                .load(R.mipmap.loading)
                .into(binding.transIv);
        binding.transTv.setText(getString(R.string.identifying_call_content));
        binding.transTv.setTextColor(ContextCompat.getColor(mContext, R.color.white));

        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(url)) {
            binding.changeModelTv.setText(mContext.getString(isDb ? R.string.db_model : R.string.ali_model));
            //  type -1 第一次拉取   0 沟通内容   1 智能需求分析   2 沟通内容重新生成（已经废弃 不重复生成）
            viewModel.getTranscription(id, url, 0, isDb ? "DB" : "ALI");
        }
    }

    /**
     * 切换豆包/阿里模型
     */
    private void changeModel() {
        if (isDb) {
            binding.dbRv.setVisibility(View.VISIBLE);
            binding.aliRv.setVisibility(View.GONE);
            dbCallTextAdapter.submitList(dbTextData);
        } else {
            aliCallTextAdapter.submitList(aliTextData);
            binding.aliRv.setVisibility(View.VISIBLE);
            binding.dbRv.setVisibility(View.GONE);
        }
        binding.transLl.setVisibility(View.GONE);
        binding.modelTipsLl.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 移除所有未执行的任务，避免内存泄漏
        handler.removeCallbacksAndMessages(null);
    }
}
